import { CraftingRecipe } from './types';
import { BlockType } from '@/blocks/types';
import { BASIC_RECIPES, RECIPE_CATEGORIES, getRecipesByCategory, getRecipesByResult, getRecipesByMaterial, searchRecipes, getRecipeStats } from './recipes';

/**
 * 配方管理器 - 提供完整的《我的世界》合成配方查询和管理功能
 */
export class RecipeManager {
  private recipes: Map<string, CraftingRecipe> = new Map();

  constructor() {
    this.loadAllRecipes();
  }

  /**
   * 加载所有配方
   */
  private loadAllRecipes(): void {
    BASIC_RECIPES.forEach(recipe => {
      this.recipes.set(recipe.id, recipe);
    });
  }

  /**
   * 获取所有配方
   */
  public getAllRecipes(): CraftingRecipe[] {
    return Array.from(this.recipes.values());
  }

  /**
   * 根据ID获取配方
   */
  public getRecipe(id: string): CraftingRecipe | undefined {
    return this.recipes.get(id);
  }

  /**
   * 根据分类获取配方
   */
  public getRecipesByCategory(category: keyof typeof RECIPE_CATEGORIES): CraftingRecipe[] {
    return getRecipesByCategory(category);
  }

  /**
   * 根据结果物品获取配方
   */
  public getRecipesByResult(blockType: BlockType): CraftingRecipe[] {
    return getRecipesByResult(blockType);
  }

  /**
   * 根据材料获取配方
   */
  public getRecipesByMaterial(blockType: BlockType): CraftingRecipe[] {
    return getRecipesByMaterial(blockType);
  }

  /**
   * 搜索配方
   */
  public searchRecipes(query: string): CraftingRecipe[] {
    return searchRecipes(query);
  }

  /**
   * 获取配方统计信息
   */
  public getStats() {
    return getRecipeStats();
  }

  /**
   * 格式化配方显示（用于调试和展示）
   */
  public formatRecipe(recipe: CraftingRecipe): string {
    const lines: string[] = [];
    lines.push(`配方: ${recipe.id}`);
    lines.push(`类型: ${recipe.type === 'shaped' ? '有形状' : '无形状'}`);
    lines.push(`结果: ${this.getBlockTypeName(recipe.result.type)} x${recipe.result.count}`);
    lines.push('合成网格:');
    
    // 显示3x3网格
    const grid = this.normalizePattern(recipe.pattern);
    for (let row = 0; row < 3; row++) {
      const rowItems: string[] = [];
      for (let col = 0; col < 3; col++) {
        const item = grid[row]?.[col];
        if (item === null || item === undefined) {
          rowItems.push('[ ]');
        } else {
          rowItems.push(`[${this.getBlockTypeName(item)}]`);
        }
      }
      lines.push(rowItems.join(' '));
    }
    
    return lines.join('\n');
  }

  /**
   * 将配方模式标准化为3x3网格
   */
  private normalizePattern(pattern: (BlockType | null)[][]): (BlockType | null)[][] {
    const normalized: (BlockType | null)[][] = [
      [null, null, null],
      [null, null, null],
      [null, null, null]
    ];

    for (let row = 0; row < Math.min(pattern.length, 3); row++) {
      for (let col = 0; col < Math.min(pattern[row]?.length || 0, 3); col++) {
        normalized[row][col] = pattern[row][col];
      }
    }

    return normalized;
  }

  /**
   * 获取方块类型的友好名称
   */
  private getBlockTypeName(blockType: BlockType): string {
    const names: Partial<Record<BlockType, string>> = {
      [BlockType.AIR]: '空气',
      [BlockType.GRASS]: '草方块',
      [BlockType.DIRT]: '泥土',
      [BlockType.STONE]: '石头',
      [BlockType.LOG]: '原木',
      [BlockType.PLANKS]: '木板',
      [BlockType.COAL_ORE]: '煤矿',
      [BlockType.LAVA]: '岩浆',
      [BlockType.FURNACE]: '熔炉',
      [BlockType.TORCH]: '火把',
      [BlockType.CRAFTING_TABLE]: '工作台',
      [BlockType.SAND]: '沙子',
      [BlockType.SANDSTONE]: '砂岩',
      [BlockType.GLASS]: '玻璃',
      [BlockType.IRON_ORE]: '铁矿',
      [BlockType.GOLD_ORE]: '金矿',
      [BlockType.DIAMOND_ORE]: '钻石矿',
      [BlockType.WATER]: '水',
      [BlockType.OBSIDIAN]: '黑曜石',
      [BlockType.REDSTONE_WIRE]: '红石线',
      [BlockType.REDSTONE_TORCH]: '红石火把',
      [BlockType.COBBLESTONE]: '圆石',
      [BlockType.GRAVEL]: '沙砾',
      [BlockType.CLAY]: '粘土',
      [BlockType.BRICK]: '砖块',
      [BlockType.SNOW]: '雪',
      [BlockType.STICK]: '木棍',
      [BlockType.COAL]: '煤炭',
      [BlockType.CHARCOAL]: '木炭',
      [BlockType.IRON_INGOT]: '铁锭',
      [BlockType.GOLD_INGOT]: '金锭',
      [BlockType.DIAMOND]: '钻石',
      [BlockType.REDSTONE_DUST]: '红石粉',
      [BlockType.STRING]: '线',
      [BlockType.FLINT]: '燧石',
      [BlockType.FEATHER]: '羽毛',
      [BlockType.LEATHER]: '皮革',
      [BlockType.SLIME_BALL]: '粘液球',
      [BlockType.BOOK]: '书',
      [BlockType.PAPER]: '纸',
      [BlockType.NETHER_QUARTZ]: '下界石英',
      [BlockType.WOODEN_PICKAXE]: '木镐',
      [BlockType.STONE_PICKAXE]: '石镐',
      [BlockType.IRON_PICKAXE]: '铁镐',
      [BlockType.GOLD_PICKAXE]: '金镐',
      [BlockType.DIAMOND_PICKAXE]: '钻石镐',
      [BlockType.WOODEN_AXE]: '木斧',
      [BlockType.STONE_AXE]: '石斧',
      [BlockType.IRON_AXE]: '铁斧',
      [BlockType.GOLD_AXE]: '金斧',
      [BlockType.DIAMOND_AXE]: '钻石斧',
      [BlockType.WOODEN_SHOVEL]: '木锹',
      [BlockType.STONE_SHOVEL]: '石锹',
      [BlockType.IRON_SHOVEL]: '铁锹',
      [BlockType.GOLD_SHOVEL]: '金锹',
      [BlockType.DIAMOND_SHOVEL]: '钻石锹',
      [BlockType.WOODEN_HOE]: '木锄',
      [BlockType.STONE_HOE]: '石锄',
      [BlockType.IRON_HOE]: '铁锄',
      [BlockType.GOLD_HOE]: '金锄',
      [BlockType.DIAMOND_HOE]: '钻石锄',
      [BlockType.SHEARS]: '剪刀',
      [BlockType.FISHING_ROD]: '钓鱼竿',
      [BlockType.FLINT_AND_STEEL]: '打火石',
      [BlockType.COMPASS]: '指南针',
      [BlockType.CLOCK]: '钟',
      [BlockType.BUCKET]: '桶',
      [BlockType.WOODEN_SWORD]: '木剑',
      [BlockType.STONE_SWORD]: '石剑',
      [BlockType.IRON_SWORD]: '铁剑',
      [BlockType.GOLD_SWORD]: '金剑',
      [BlockType.DIAMOND_SWORD]: '钻石剑',
      [BlockType.BOW]: '弓',
      [BlockType.ARROW]: '箭',
      [BlockType.CROSSBOW]: '弩',
      [BlockType.SHIELD]: '盾牌',
      [BlockType.LEATHER_HELMET]: '皮革头盔',
      [BlockType.LEATHER_CHESTPLATE]: '皮革胸甲',
      [BlockType.LEATHER_LEGGINGS]: '皮革护腿',
      [BlockType.LEATHER_BOOTS]: '皮革靴子',
      [BlockType.IRON_HELMET]: '铁头盔',
      [BlockType.IRON_CHESTPLATE]: '铁胸甲',
      [BlockType.IRON_LEGGINGS]: '铁护腿',
      [BlockType.IRON_BOOTS]: '铁靴子',
      [BlockType.GOLD_HELMET]: '金头盔',
      [BlockType.GOLD_CHESTPLATE]: '金胸甲',
      [BlockType.GOLD_LEGGINGS]: '金护腿',
      [BlockType.GOLD_BOOTS]: '金靴子',
      [BlockType.DIAMOND_HELMET]: '钻石头盔',
      [BlockType.DIAMOND_CHESTPLATE]: '钻石胸甲',
      [BlockType.DIAMOND_LEGGINGS]: '钻石护腿',
      [BlockType.DIAMOND_BOOTS]: '钻石靴子',
      [BlockType.CHEST]: '箱子',
      [BlockType.WOODEN_STAIRS]: '木楼梯',
      [BlockType.STONE_STAIRS]: '石楼梯',
      [BlockType.WOODEN_SLAB]: '木台阶',
      [BlockType.STONE_SLAB]: '石台阶',
      [BlockType.WOODEN_DOOR]: '木门',
      [BlockType.IRON_DOOR]: '铁门',
      [BlockType.WOODEN_TRAPDOOR]: '木活板门',
      [BlockType.IRON_TRAPDOOR]: '铁活板门',
      [BlockType.WOODEN_FENCE]: '木栅栏',
      [BlockType.GLASS_PANE]: '玻璃板',
      [BlockType.IRON_BARS]: '铁栏杆',
      [BlockType.BOOKSHELF]: '书架',
      [BlockType.REDSTONE_REPEATER]: '红石中继器',
      [BlockType.REDSTONE_COMPARATOR]: '红石比较器',
      [BlockType.PISTON]: '活塞',
      [BlockType.STICKY_PISTON]: '粘性活塞',
      [BlockType.POWERED_RAIL]: '动力铁轨',
      [BlockType.DETECTOR_RAIL]: '探测铁轨',
      [BlockType.RAIL]: '铁轨',
      [BlockType.STONE_PRESSURE_PLATE]: '石质压力板',
      [BlockType.WOODEN_PRESSURE_PLATE]: '木质压力板',
      [BlockType.LEVER]: '拉杆',
      [BlockType.BUTTON]: '按钮',
      [BlockType.TRIPWIRE_HOOK]: '绊线钩',
      [BlockType.MINECART]: '矿车',
      [BlockType.BOAT]: '船'
    };

    return names[blockType] || `未知物品(${blockType})`;
  }

  /**
   * 打印所有配方（用于调试）
   */
  public printAllRecipes(): void {
    console.log('=== 《我的世界》完整合成配方表 ===\n');
    
    Object.entries(RECIPE_CATEGORIES).forEach(([categoryName, recipeIds]) => {
      console.log(`\n=== ${categoryName} ===`);
      const categoryRecipes = this.getRecipesByCategory(categoryName as keyof typeof RECIPE_CATEGORIES);
      categoryRecipes.forEach(recipe => {
        console.log('\n' + this.formatRecipe(recipe));
        console.log('-'.repeat(50));
      });
    });

    const stats = this.getStats();
    console.log(`\n=== 统计信息 ===`);
    console.log(`总配方数: ${stats.total}`);
    console.log(`分类数: ${stats.categories}`);
    stats.byCategory.forEach(cat => {
      console.log(`${cat.name}: ${cat.count} 个配方`);
    });
  }
}